package cn.flying.cloud.message.core.email;

import javax.mail.internet.MimeMessage;

import java.io.File;
import java.security.GeneralSecurityException;
import java.util.Objects;
import java.util.Properties;

import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import com.sun.mail.util.MailSSLSocketFactory;

import cn.flying.cloud.base.common.utils.Ft;
import cn.flying.cloud.base.mail.exception.MsgException;
import cn.flying.cloud.message.bo.MsgStorageBo;
import cn.flying.cloud.message.core.enums.SendType;
import cn.flying.cloud.message.core.strategy.MessageSenderStrategy;
import cn.flying.cloud.message.model.MessageRequest;

/**
 * 发送邮件消息
 *
 * @author: admin
 * @date: 2025年03月29日 20:40
 * @version: 1.0
 */
@Component
public class EmailMessageSenderStrategy implements MessageSenderStrategy {


    /**
     * 发送消息
     *
     * @param request
     * @param sendType
     * @return
     */
    @Override
    public boolean sender(MessageRequest request, MsgStorageBo storage, SendType sendType, boolean html) {
        try {
            // 邮件发送实现类
            JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
            mailSender.setProtocol(Ft.String.isBlank(storage.getProtocol()) ? "smtp" : storage.getProtocol());
            mailSender.setHost(storage.getEndpoint());
            mailSender.setPort(storage.getPort() == null ? 25 : storage.getPort());
            mailSender.setUsername(storage.getAccessKey());
            mailSender.setPassword(storage.getSecretKey());
            mailSender.setDefaultEncoding("UTF-8");

            setProperties(storage, mailSender);

            //获取MimeMessage对象
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            //邮件发送人（这里要和认证用户邮箱匹配）
            helper.setFrom(storage.getAccessKey());
            //邮件接收人
            helper.setTo(request.getRecipients().toArray(new String[0]));
            //邮件主题
            message.setSubject(request.getTitle());
            //邮件内容，html格式
            helper.setText(request.getContent(), html);
            //可以同时添加多个附件
            if (request.getFilePaths() != null) {
                for (String path : request.getFilePaths()) {
                    FileSystemResource resource = new FileSystemResource(new File(path));
                    helper.addAttachment(Objects.requireNonNull(resource.getFilename()), resource);
                }
            }

            //发送
            mailSender.send(message);

            logger.info("邮件已经发送成功！");
            return true;
        } catch (Exception e) {
            logger.error("邮件发送失败，原因：[{}]", e.getMessage());
            throw new MsgException("邮件发送失败！", e);
        }
    }

    private static void setProperties(MsgStorageBo storage, JavaMailSenderImpl mailSender) throws GeneralSecurityException {
        Properties props = mailSender.getJavaMailProperties();
        // 25 端口
        // props.put("mail.smtp.auth", "true");
        // props.put("mail.smtp.starttls.enable", "false");
        // props.put("mail.smtp.ssl.enable", "false");

        // 465 端口
        // props.put("mail.smtp.auth", "true");
        // props.put("mail.smtp.starttls.enable", "false");
        // props.put("mail.smtp.ssl.enable", "true");

        // 587 端口
        // props.put("mail.smtp.auth", "true");
        // props.put("mail.smtp.starttls.enable", "true");
        // props.put("mail.smtp.starttls.required", "true");
        // props.put("mail.smtp.ssl.enable", "false");

        if (storage.getPort() != null && 25 != storage.getPort()) {
            props.put("mail.smtp.auth", "true");
        }
        // starttls
        if ("Y".equals(storage.getIsStarttls())) {
            props.put("mail.smtp.starttls.enable", "true");
            props.put("mail.smtp.starttls.required", "true");
        } else {
            props.put("mail.smtp.starttls.enable", "false");
            props.put("mail.smtp.starttls.required", "false");
        }
        // ssl
        if ("Y".equals(storage.getIsSsl())) {
            MailSSLSocketFactory sf = new MailSSLSocketFactory("TLSv1.2");
            sf.setTrustAllHosts(true);
            props.put("mail.smtp.ssl.enable", "true");
            props.put("mail.smtp.ssl.socketFactory", sf);
        } else {
            props.put("mail.smtp.ssl.enable", "false");
        }
    }

    /**
     * 获取名称
     *
     * @return
     */
    @Override
    public String getName() {
        return "email";
    }
}
